#!/usr/bin/env python3
"""
修复录制脚本中的固定token，改为动态获取
用法：python pwl/fix_token.py [script_file]
"""

import os
import sys
import re
import glob
from urllib.parse import urlparse

def fix_script_token(script_path: str) -> bool:
    """
    修复单个脚本文件中的token
    :param script_path: 脚本文件路径
    :return: 是否修复成功
    """
    try:
        print(f"🔧 修复脚本: {os.path.basename(script_path)}")
        
        # 读取脚本内容
        with open(script_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 检查是否已经修复过
        if 'get_current_token()' in content:
            print(f"✅ 脚本已经支持动态token，跳过修复")
            return True
        
        # 查找page.goto行
        goto_pattern = r'page\.goto\("([^"]+)"\)'
        goto_match = re.search(goto_pattern, content)
        
        if not goto_match:
            print(f"⚠️ 未找到page.goto调用，跳过修复")
            return False
        
        original_url = goto_match.group(1)
        print(f"🌐 原始URL: {original_url}")
        
        # 提取基础URL
        if '?token=' in original_url:
            base_url = original_url.split('?token=')[0]
        else:
            parsed_url = urlparse(original_url)
            base_url = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
        
        print(f"🔗 基础URL: {base_url}")
        
        # 替换page.goto调用
        def replace_goto(match):
            return f'''# 动态获取token并构建URL
    token = get_current_token()
    url = f"{base_url}" + f"?token={{token}}"
    print(f"🌐 访问URL: {{url}}")
    page.goto(url)'''
        
        new_content = re.sub(goto_pattern, replace_goto, content)
        
        # 添加token获取函数
        token_function = '''
def get_current_token():
    """从配置文件获取当前有效的token"""
    import os
    import configparser
    
    try:
        # 获取项目根目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        base_dir = os.path.dirname(current_dir)
        
        # 确定环境
        env = os.environ.get('ENV', 'test')
        config_path = os.path.join(base_dir, 'common', f'config.{env}.ini')
        
        print(f"📖 读取配置文件: {config_path}")
        
        # 读取配置文件
        config = configparser.ConfigParser()
        config.read(config_path, encoding='utf-8')
        
        token = config.get('token', 'access_token', fallback=None)
        if not token:
            raise ValueError("配置文件中未找到有效token")
            
        print(f"✅ 获取到token: {token[:20]}...")
        return token
        
    except Exception as e:
        print(f"❌ 获取token失败: {e}")
        print("⚠️ 使用默认token，可能导致访问失败")
        return "default-token"
'''
        
        # 在import之后添加token获取函数
        import_end = new_content.find('\n\n')
        if import_end != -1:
            new_content = new_content[:import_end] + token_function + new_content[import_end:]
        else:
            new_content = token_function + '\n' + new_content
        
        # 写回文件
        with open(script_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print(f"✅ 脚本修复完成")
        return True
        
    except Exception as e:
        print(f"❌ 修复失败: {e}")
        return False

def fix_all_scripts():
    """修复pwl文件夹下的所有录制脚本"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 查找所有录制脚本
    patterns = [
        os.path.join(current_dir, "test_record_*.py"),
        os.path.join(current_dir, "test_*.py")
    ]
    
    all_scripts = []
    for pattern in patterns:
        scripts = glob.glob(pattern)
        all_scripts.extend(scripts)
    
    # 过滤掉工具脚本
    exclude_files = ['run.py', 'execute_scripts.py', 'fix_token.py', 'script_template.py']
    scripts_to_fix = []
    
    for script in all_scripts:
        filename = os.path.basename(script)
        if filename not in exclude_files:
            scripts_to_fix.append(script)
    
    if not scripts_to_fix:
        print("❗ 未找到需要修复的录制脚本")
        return
    
    print(f"🔍 找到 {len(scripts_to_fix)} 个录制脚本:")
    for script in scripts_to_fix:
        print(f"  - {os.path.basename(script)}")
    
    print("\n🚀 开始修复...")
    success_count = 0
    
    for script in scripts_to_fix:
        if fix_script_token(script):
            success_count += 1
        print()
    
    print(f"🎉 修复完成: {success_count}/{len(scripts_to_fix)} 个脚本修复成功")

def main():
    if len(sys.argv) > 1:
        # 修复指定脚本
        script_path = sys.argv[1]
        if os.path.exists(script_path):
            fix_script_token(script_path)
        else:
            print(f"❌ 文件不存在: {script_path}")
    else:
        # 修复所有脚本
        fix_all_scripts()

if __name__ == "__main__":
    main()
